<script setup>
import { getCurrentInstance, reactive, ref } from 'vue';
import { register, sendSms } from '@/api/user.js';
import { useRouter } from 'vue-router';

const instance = getCurrentInstance();
const { $message } = instance.appContext.config.globalProperties;
const router = useRouter();

const form = reactive({
  account: '', // 账号
  password: '', // 密码
  identifyingCode: '', // 验证码
});
const accountError = ref(false); // 账号报错
const identifyingCodeError = ref(false); // 验证码报错
const passwordError = ref(false); // 密码报错
// 设置输入框输入报错取消
function setInputError(code) {
  switch (code) {
    case 'account':
      accountError.value = false;
      break;
    case 'password':
      passwordError.value = false;
      break;
    case 'identifyingCode':
      identifyingCodeError.value = false;
      break;
  }
}
const phoneRex = /^1[3-9][0-9]{9}$/;
const sendCodeAgain = ref(true); // 是否可以再次发送验证码
const codeWord = ref('获取验证码'); // 发送验证码的文字
let uuid = '';
// 校验账户信息
function checkAccount() {
  if (form.account === '') {
    $message.error('账号信息为空，请输入账号！');
    accountError.value = true;
    return false;
  }
  if (!phoneRex.test(form.account)) {
    $message.error('账号信息输入错误，请输入手机号！');
    accountError.value = true;
    return false;
  }
  return true;
}
// 发送验证码
async function sendCode() {
  if (!checkAccount()) {
    return false;
  }
  if (sendCodeAgain.value) {
    let seconds = 60;
    sendCodeAgain.value = false;
    const timer = setInterval(function () {
      seconds -= 1; // 每秒减去1
      codeWord.value = `${seconds}后重新发送`;

      if (seconds <= 0) {
        clearInterval(timer); // 时间到达后清除定时器
        codeWord.value = '重新发送'; // 更新显示文本
        sendCodeAgain.value = true;
      }
    }, 1000);
  }
  const returnData = await sendSms({ userName: form.account, uuid, type: 'register' });
  console.log(returnData);
  if (returnData?.code !== 200) {
    $message.error(returnData?.msg);
  } else {
    uuid = returnData?.data?.uuid;
  }
}
// 注册按钮点击
async function handleSubmit() {
  if (!checkAccount()) {
    return false;
  }
  const { identifyingCode, password } = form;
  if (identifyingCode === '') {
    identifyingCodeError.value = true;
    $message.error('验证码为空，请输入验证码！');
    return false;
  }
  if (password === '') {
    passwordError.value = true;
    $message.error('密码为空，请输入密码！');
    return false;
  }
  const returnData = await register({
    userName: form.account,
    uuid,
    password,
    code: identifyingCode,
  });
  console.log(returnData);
  if (returnData?.code !== 200) {
    $message.error(returnData?.msg);
  } else {
    $message({
      type: 'success',
      message: '注册成功,即将跳转到登录界面',
      onClose() {
        router.push({ path: '/login' });
      },
    });
  }
}
// 返回登录按钮点击
function handleGoBack() {
  router.push({ path: '/login' });
}
// 忘记密码
function forgetHandle() {
  router.push({ path: '/forgetPassword' });
}
</script>

<template>
  <div class="register-box">
    <div class="login-content">
      <div class="title">欢迎注册！</div>
      <div class="form-box">
        <div class="account-box login-form-box" :class="{ error: accountError }">
          <img src="../../assets/images/common/account-icon.png" alt="" />
          <el-input
            v-model="form.account"
            placeholder="请输入账号"
            @input="setInputError('account')"
          />
        </div>
        <div class="code-box">
          <div class="login-form-box" :class="{ error: identifyingCodeError }">
            <img src="../../assets/images/register/email-icon.png" alt="" />
            <el-input
              v-model="form.identifyingCode"
              placeholder="请输入验证码"
              @input="setInputError('identifyingCode')"
            />
          </div>
          <el-button @click="sendCode" :disabled="!sendCodeAgain">{{ codeWord }}</el-button>
        </div>
        <div class="password-box login-form-box" :class="{ error: passwordError }">
          <img src="../../assets/images/common/password-icon.png" alt="" />
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            type="password"
            @input="setInputError('password')"
          />
        </div>
        <div class="forget-password-box">
          <span @click="forgetHandle">忘记密码？</span>
        </div>
        <div class="login-btn-box">
          <div class="btn back-btn" @click="handleGoBack">返回登录</div>
          <div class="login-btn btn" @click="handleSubmit">确定</div>
        </div>
      </div>
    </div>
    <div class="footer">
      <img src="../../assets/images/common/project-icon.png" alt="" />
      <span>本服务由学术进修课堂提供</span>
    </div>
  </div>
</template>

<style scoped lang="less">
@import './register';
</style>
